<template>
    <page
    navbar
    title="运行环境设置"
    >
        <van-cell-group title="点击切换运行环境设置">
            <van-cell center  :title="envNames[item.env]" :label="getDomain(item)" v-for="(item, index) in envs" @click="setEnv(item)" :key="index">
                <van-icon name="success" v-if="url==getDomain(item)" />
            </van-cell>
        </van-cell-group>
        <div class="mt10">
            <van-button type="primary" block @click="clearEnv">清除环境设置</van-button>
        </div>
    </page>
</template>

<script>
import Config from '@/api/config'
import { Dialog } from 'vant'
import {useRouter} from 'vue-router'
import { ref } from 'vue'
export default {
    beforeRouteEnter(to, from, next){
        if(localStorage.getItem('env')){
            next()
        } else {
            next({name:'home', replace:true})
        }
    },
    setup(){
        const envNames = {'prod':'生产环境', 'pre':'预发布环境', 'test':'测试环境', 'dev':'开发环境'}
        const router = useRouter()
        function getDomain(env){
            return `${env.isHttps?'https://':'http://'}${env.domain}`
        }
        function setEnv(env){
            Dialog.confirm({
                title: '确认框',
                message: '确定要切换到当前环境吗？',
                closeOnClickOverlay:true
            }).then(action=>{
                localStorage.setItem('env', env.env)
                router.replace({name:'home'})
                setTimeout(()=>{location.reload(true)},0)
            }).catch(() => {})
        }
        function clearEnv(){
            Dialog.confirm({
                title: '确认框',
                message: '确定要清除当前环境设置吗？',
                closeOnClickOverlay:true
            }).then(action=>{
                localStorage.removeItem('env')
                router.replace({name:'home'})
                setTimeout(()=>{location.reload(true)},0)
            }).catch(() => {})
        }
        return {
            envs:Config.envs,
            url:Config.url,
            envNames,
            getDomain,
            setEnv,
            clearEnv
        }
    }
}
</script>